import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/article_item.dart';
import 'package:flutter_syt/datas/game_item.dart';
import 'package:flutter_syt/datas/provider_index_setting.dart';
import 'package:flutter_syt/datas/venue_item.dart';
import 'package:flutter_syt/domain/games/event_schedule_model.dart';
import 'package:flutter_syt/domain/widgets/flow_item.dart';
import 'package:flutter_syt/domain/widgets/network_load_image.dart';
import 'package:flutter_syt/domain/widgets/stupid_tabs.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/widgets/normal_table.dart';
import 'package:flutter_syt/widgets/text_highliigh_widget.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "search")
class SearchPage extends StatefulWidget {
  final bool isCompetitions; //是否是观赛
  SearchPage({this.isCompetitions = false});
  @override
  State<StatefulWidget> createState() {
    return _SearchState();
  }
}

class _SearchState extends State<SearchPage>
    with RouteAware, SingleTickerProviderStateMixin {
  List<String> keywords = [];
  bool isSearching = false;
  TextEditingController _searchController = TextEditingController();
  FocusNode _searchFocus = FocusNode();
  String _searchKey = "";
  NormalTableViewController _newsTableController = NormalTableViewController();
  NormalTableViewController _venueTableController = NormalTableViewController();
  NormalTableViewController _sportsTableController =
      NormalTableViewController();
  NormalTableViewController _matchTableController = NormalTableViewController();
  SystemUiOverlayStyle? _oldStyle;
  late TabController _tabController;
  @override
  void dispose() {
    appContext.rootObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    var route = ModalRoute.of<dynamic>(context);
    if (route != null) {
      appContext.rootObserver.subscribe(this, route);
    }
    super.didChangeDependencies();
  }

  @override
  void didPush() {
    super.didPush();
  }

  @override
  void didPopNext() {
    super.didPopNext();
  }

  @override
  void didPop() {
    if (_oldStyle != null) {
      SystemChrome.setSystemUIOverlayStyle(_oldStyle!);
    }

    super.didPop();
  }

  @override
  void initState() {
    // ProviderIndexSetting().indexSetting.gameSchedule = 0;
    _oldStyle = SystemChrome.latestStyle;

    try {
      var keys = appContext.storage.getString("recent_search_keys") ?? "";
      keywords = (json.decode(keys) as List).map((e) => "$e").toList();
      // debugPrint("the keys is -- $keywords");
    } catch (e) {
      // debugPrint("the keys is -- $e");
    }
    // _searchFocus.addListener(() {
    //   if (_searchFocus.hasFocus) {
    //     setState(() {
    //       // isSearching = true;
    //     });
    //   }
    // });
    // _searchController.addListener(() {});
    _tabController = TabController(
        length: ProviderIndexSetting().indexSetting.gameSchedule == 1 ? 4 : 1,
        vsync: this);
    if (ProviderIndexSetting().indexSetting.gameSchedule == 1 &&
        widget.isCompetitions) {
      _tabController.animateTo(3);
    }
    super.initState();
  }

  onSearch() {
    _searchFocus.unfocus();
    keywords.remove(_searchKey);
    keywords.insert(0, _searchKey);
    if (keywords.length > 10) {
      keywords = keywords.sublist(0, 9);
    }
    var result = json.encoder.convert(keywords);
    appContext.storage.setString("recent_search_keys", result);
    // _controller.reloadData();
    // if (_tabController.index == 0) {
    _newsTableController.reloadData();
    // } else if (_tabController.index == 1) {
    _venueTableController.reloadData();
    // } else if (_tabController.index == 2) {
    _sportsTableController.reloadData();
    // } else if (_tabController.index == 3) {
    _matchTableController.reloadData();

    // }
  }

  Widget _searchBar() {
    return Container(
      child: SafeArea(
        bottom: false,
        child: Column(
          children: [
            Container(
              height: 44,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    width: 44,
                    child: IconButton(
                      onPressed: ClickUtils.debounce(() {
                        Navigator.of(context).pop();
                      }),
                      icon: Icon(Icons.arrow_back),
                    ),
                  ),
                  Expanded(
                      child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Container(
                        height: 32,
                        decoration: const BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(16)),
                          color: Color(0xfff4f4f4),
                        ),
                      ),
                      SizedBox(
                        height: 40,
                        child: Row(
                          children: [
                            const  Padding(
                              padding: EdgeInsets.only(left: 12),
                            ),
                            Image.asset(
                              "assets/icons/icon_search_black.png",
                              width: 16,
                              height: 16,
                            ),
                            const     Padding(padding: EdgeInsets.only(right: 6)),
                            Expanded(
                              child: TextField(
                                inputFormatters: [
                                  FilteringTextInputFormatter.deny(
                                      appContext.emojiRegexp)
                                ],
                                enableInteractiveSelection: true,
                                maxLength: 20,
                                onSubmitted: (e) {
                                  var tmp = e.trim();
                                  if (tmp.isEmpty) {
                                    return;
                                  }
                                  setState(() {
                                    isSearching = true;
                                  });
                                  _searchKey = tmp;
                                  onSearch();
                                },
                                textInputAction: TextInputAction.search,
                                controller: _searchController,
                                focusNode: _searchFocus,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: S.of(context).enter_keywords,
                                  hintStyle: const TextStyle(
                                    fontSize: 14,
                                    color: ThemeColor.colorTextB5,
                                  ),
                                  counterText: "",
                                  contentPadding: EdgeInsets.zero,
                                  isCollapsed: true
                                ),
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Colors.black,
                                ),
                              ),
                            ),
                            const Padding(padding: EdgeInsets.only(right: 6)),
                          ],
                        ),
                      ),
                    ],
                  )),
                  GestureDetector(
                    onTap: ClickUtils.debounce(() {
                      if (isSearching) {
                        _searchFocus.unfocus();
                        _searchController.clear();
                        setState(() {
                          isSearching = false;
                        });
                      } else {
                        Navigator.of(context).pop();
                      }
                    }),
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      height: 35,
                      // color: Colors.red,
                      padding: EdgeInsets.only(left: 16, right: 16),
                      alignment: Alignment.center,
                      child: Text(
                        S.of(context).Cancel,
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff666666),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Divider(
              height: 1,
              color: Color(0xffeeeeee),
            ),
          ],
        ),
      ),
    );
  }

  Widget _showHolder() {
    return ViewStateWidget(
      image: Image.asset(
        "assets/images/empty.png",
        width: 140,
        height: 140,
      ),
      title: 'No search results', //暂无数据
      isShowRefreshBtn: false,
    );
  }

  Widget _buildTabbarWidget() {
    return Expanded(
      child: TabBarView(
        controller: _tabController,
        children: (ProviderIndexSetting().indexSetting.gameSchedule == 1)
            ? [
                _searchArticleResult(),
                _buildVenueWidget(),
                _buildGamesWidget(),
                _buildScheduleWidget(),
              ]
            : [_searchArticleResult()],
      ),
    );
  }

  Widget _searchArticleResult() {
    return NormalTableView<ArticleListItem>(
      // needAutoFreash: true,
      controller: _newsTableController,
      itemBuilder: (ctx, item) {
        var entity = FlowItemEntity();
        entity.createTime = item.publish_time;
        entity.text = item.title;
        entity.imageUrl = item.thumb;
        entity.labelText = "";
        return GestureDetector(
          child: FlowItem(
            entity,
            searchStr: _searchKey,
          ),
          onTap: ClickUtils.debounce(
              () => RouteManager.push(context, item.linkUrl)),
        );
      },
      getData: (page) async {
        var list =
            await API.shared.article.articleList(page, search: _searchKey);
        print(list);

        return list;
      },
    );
  }

  Widget _buildVenueWidget() {
    return NormalTableView<VenueItem>(
      controller: _venueTableController,
      getData: (page) async {
        return await API.shared.venue.list(search: _searchKey);
      },
      enableLoadMore: false,
      itemBuilder: (context, item) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: ClickUtils.debounce(() =>
              RouteManager.push(context, RoutMapping.venueDetailPage(item.id))),
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 15.w),
                child: Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(8.w),
                      child: NetworkLoadImage.loadNetworkImage(
                        // CachedNetworkImage(
                        // imageUrl:
                        item.cover,
                        width: 80.w,
                        height: 80.w,
                        fit: BoxFit.cover,
                      ),
                    ),
                    SizedBox(
                      width: 15.w,
                    ),
                    Expanded(
                        //   child: Text(
                        // item.name,
                        // maxLines: 2,
                        // overflow: TextOverflow.ellipsis,
                        // style: TextStyle(color: Colors.black, fontSize: 16),
                        // )
                        child: TextHighlightWidget(
                      item.name,
                      _searchKey,
                      FontStyles.headerTextStyle_16,
                      FontStyles.headerTextStyle_16
                          .copyWith(color: ThemeColor.primaryColor),
                    ))
                    // CachedNetworkImage(imageUrl: imageUrl)
                  ],
                ),
              ),
              Container(
                height: 1,
                color: Color(0xffEFEFEF),
              )
            ],
          ),
        );
      },
    );
  }

  Widget _buildGamesWidget() {
    return NormalTableView<GameDetail>(
      // pageSize: (page) => 200,
      // crossAxisCount: 3,
      controller: _sportsTableController,
      // mainAxisSpacing: 10,
      padding: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
      // crossAxisSpacing: 10,
      enableLoadMore: false,
      itemBuilder: (content, item) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: ClickUtils.debounce(() {
            RouteManager.push(context, item.path);
          }),
          // RouteManager.push(context, RoutMapping.venueDetailPage(item.id)),
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 15.w),
                child: Row(
                  children: [
                    Stack(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(8.w),
                          child: NetworkLoadImage.loadNetworkImage(
                            //  CachedNetworkImage(
                            // imageUrl:
                            item.background,
                            width: 64.w,
                            height: 64.w,
                            fit: BoxFit.cover,
                            // errorWidget: (ctc, error, child) {
                            //   return Container(
                            //     color: Colors.grey,
                            //   );
                            // },
                          ),
                        ),
                        Positioned.fill(
                            child: Center(
                          child: NetworkLoadImage.loadNetworkImage(
                            // CachedNetworkImage(
                            // imageUrl:
                            item.cover,
                            width: 44.w,
                            height: 44.w,
                            // fit: BoxFit.cover,
                            // errorWidget: (ctc, error, child) {
                            //   return Container(
                            //     color: Colors.grey,
                            //   );
                            // },
                          ),
                        ))
                      ],
                    ),
                    SizedBox(
                      width: 15.w,
                    ),
                    Expanded(
                        child: TextHighlightWidget(
                      item.discipline_name,
                      _searchKey,
                      FontStyles.headerTextStyle_16,
                      FontStyles.headerTextStyle_16
                          .copyWith(color: ThemeColor.primaryColor),
                    ))
                    // CachedNetworkImage(imageUrl: imageUrl)
                  ],
                ),
              ),
              Container(
                height: 1,
                color: Color(0xffEFEFEF),
              )
            ],
          ),
        );
      },
      // itemBuilder: (ctx, item, index) {
      // return Container(
      //     height: 103,
      //     child: GestureDetector(
      //       child: Column(
      //         crossAxisAlignment: CrossAxisAlignment.center,
      //         children: [
      //           ClipRRect(
      //             borderRadius: BorderRadius.circular(30.w),
      //             child: Stack(
      //               children: [
      //                 CachedNetworkImage(
      //                   imageUrl: item.background,
      //                   width: 60.w,
      //                   height: 60.w,
      //                   fit: BoxFit.cover,
      //                   errorWidget: (ctc, error, child) {
      //                     return Container(
      //                       color: Colors.grey,
      //                     );
      //                   },
      //                 ),
      //                 Positioned.fill(
      //                   child: Center(
      //                     child: CachedNetworkImage(
      //                       imageUrl: item.cover,
      //                       width: 45.w,
      //                       height: 45.w,
      //                       fit: BoxFit.cover,
      //                       errorWidget: (ctc, error, child) {
      //                         return Container(
      //                           color: Colors.grey,
      //                         );
      //                       },
      //                     ),
      //                   ),
      //                 )
      //               ],
      //             ),
      //           ),
      //           Padding(padding: EdgeInsets.only(top: 5.w)),
      //           Container(
      //             // height: 28,
      //             // margin: EdgeInsets.only(bottom: 10.w),
      //             child: Text(
      //               item.discipline_name,
      //               maxLines: 2,
      //               textAlign: TextAlign.center,
      //               overflow: TextOverflow.ellipsis,
      //               style: TextStyle(color: Colors.black, fontSize: 14),
      //             ),
      //           ),
      //         ],
      //       ),
      //       behavior: HitTestBehavior.opaque,
      //       onTap: () {
      //         RouteManager.push(context, item.path);
      //       },
      //     ),
      //   );
      // },
      getData: (page) async {
        return await API.shared.game.items(search: _searchKey);
      },
    );
  }

  Widget _buildScheduleWidget() {
    return NormalTableView<EventScheduleData>(
      // needAutoFreash: true,
      controller: _matchTableController,
      itemBuilder: (ctx, item) {
        return GestureDetector(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 17.w),
            height: 115,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Text(
                          item.date,
                          style: TextStyle(
                            color: ThemeColor.colorBlack60,
                            fontSize: 14,
                          ),
                        ),
                        SizedBox(
                          width: 8,
                        ),
                        Text(
                          item.time,
                          style: TextStyle(
                            color: ThemeColor.colorBlack100,
                            fontSize: 14,
                          ),
                        )
                      ],
                    ),
                    Text(
                      item.statusName,
                      style: TextStyle(
                        color: ThemeColor.colorBlack40,
                        fontSize: 11,
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Container(
                        width: 48.w,
                        height: 48.w,
                        child: Stack(
                          children: [
                            NetworkLoadImage.loadNetworkImage(
                              // CachedNetworkImage(
                              // imageUrl:
                              item.background,
                            ),
                            Positioned.fill(
                                child: Center(
                              child: NetworkLoadImage.loadNetworkImage(
                                item.cover,
                                //  CachedNetworkImage(
                                width: 36.w,
                              ),
                            ))
                          ],
                        )),
                    SizedBox(
                      width: 15.w,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                            constraints: BoxConstraints(maxWidth: 240.w),
                            child: Text(
                              "${item.disciplineName} ${item.scheduleName}",
                              style: TextStyle(
                                color: ThemeColor.colorBlack100,
                                fontSize: 16,
                              ),
                            )),
                        // SizedBox(
                        //   height: 10,
                        // ),
                        Row(children: [
                          Image.asset("assets/icons/schedule_location.png",
                              width: 10, height: 11),
                          SizedBox(
                            width: 4,
                          ),
                          // Expanded(
                          // child:
                          Container(
                            constraints: BoxConstraints(maxWidth: 240.w),
                            // child: Text(
                            //   item.venueName,
                            //   maxLines: 1,
                            //   overflow: TextOverflow.ellipsis,
                            //   style: TextStyle(
                            //       fontSize: 12, color: Colors.black38),
                            // ),
                            child: TextHighlightWidget(
                              item.venueName,
                              _searchKey,
                              FontStyles.headerTextStyle_16,
                              FontStyles.headerTextStyle_16
                                  .copyWith(color: ThemeColor.primaryColor),
                            ),
                          )
                          // ),
                        ])
                      ],
                    )
                  ],
                )
              ],
            ),
          ),
          behavior: HitTestBehavior.opaque,
          onTap: ClickUtils.debounce(() => RouteManager.push(
              context, RoutMapping.gameDetail(item.id, isVideo: false))),
        );
      },

      getData: (page) async {
        var list = await API.shared.game
            .scheduleList(true, page, 20, '', '', '', '', search: _searchKey);
        return list.map((e) => EventScheduleData(e)).toList();
      },
    );
  }

  Widget keywordsList() {
    List<Widget> children = keywords
        .map(
          (e) => GestureDetector(
            onTap: ClickUtils.debounce(() {
              setState(() {
                isSearching = true;
              });
              _searchKey = e;
              _searchController.text = e;
              onSearch();
            }),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  height: 30,
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(4)),
                    border: Border.all(
                        color: Colors.black.withOpacity(0.1), width: 0.5),
                    color: Colors.white,
                  ),
                  child: Text(
                    e,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 14,
                      color: Color(0xff666666),
                    ),
                    strutStyle: StrutStyle(
                      fontSize: 14,
                      leading: 0,
                      forceStrutHeight: true,
                    ),
                  ),
                )
              ],
            ),
          ),
        )
        .toList();
    return Column(
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          height: 50,
          alignment: Alignment.centerLeft,
          child: Row(
            children: [
              Text(S.of(context).search_history),
              Spacer(),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: ClickUtils.debounce(() {
                  setState(() {
                    keywords.clear();
                    appContext.storage.setString("recent_search_keys", '');
                  });
                }),
                child: Image.asset(
                  "assets/icons/del.png",
                  width: 16,
                  height: 16,
                ),
              )
            ],
          ),
        ),
        Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(
            horizontal: 16,
          ),
          child: Wrap(
            spacing: 10,
            runSpacing: 10,
            children: children,
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      color: Colors.white,
      width: 1.sw,
      height: 1.sh,
      child: Column(
        children: [
          _searchBar(),
          isSearching
              ? Container(
                  // padding: EdgeInsets.only(top: 10, bottom: 10),
                  child: NormalTabs(
                    (ProviderIndexSetting().indexSetting.gameSchedule == 1)
                        ? [
                            ScrollerTabEntity.create(
                                'type', S.current.search_information, 0, ''),
                            ScrollerTabEntity.create(
                                'type', S.current.search_site, 0, ''),
                            ScrollerTabEntity.create(
                                'type', S.current.search_project, 0, ''),
                            ScrollerTabEntity.create(
                                'type', S.current.search_schedule, 0, '')
                          ]
                        : [
                            ScrollerTabEntity.create(
                                'type', S.current.search_information, 0, ''),
                          ],
                    _tabController,
                    textColor: Colors.black,
                    // alignment: Alignment.centerLeft,
                  ),
                )
              : Container(),
          isSearching ? _buildTabbarWidget() : keywordsList(),
        ],
      ),
    ));
  }
}
